package cn.tedu.knows.portal.controller;


import cn.tedu.knows.portal.exception.ServiceException;
import cn.tedu.knows.portal.model.Comment;
import cn.tedu.knows.portal.service.ICommentService;
import cn.tedu.knows.portal.vo.CommentVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.awt.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2021-10-27
 */
@RestController
@RequestMapping("/v1/comments")
@Slf4j
public class CommentController {


    @Autowired
    private ICommentService commentService;

    @PostMapping
    public Comment addComment(
            @AuthenticationPrincipal UserDetails user,
            @Validated CommentVo commentVo,
            BindingResult result){
        log.debug("接收到 用户信息:{}",commentVo);
        if (result.hasErrors()){
            String msg = result.getFieldError().getDefaultMessage();
            throw new ServiceException(msg);
        }
        Comment comment = commentService.saveComment(commentVo,user.getUsername());
        return comment;
    }
    @GetMapping("/delete/{id}")
   public String removeComment(@PathVariable Integer id,
                               @AuthenticationPrincipal UserDetails user){
        if (commentService.removeComment(id,user.getUsername())){
            return "ok";
        }else {
            return "fail";
        }
    }
}
